import { Checkbox, DatePicker, Form, Input, InputNumber, Modal } from "antd";
import dayjs from "dayjs";
import NP from "number-precision";
import { useEffect } from "react";
import { apiAddChannelRevenue, apiModifyChannelRevenue } from "~/api/channel";
import Title from "~/components/ui/title";
import type {
  IChannelMonthlyRevenue,
  IChannelRevenue,
} from "~/types/manage/channel/coin";
import { amountToFen, amountToYuan, calculateTaxAmount } from "~/utils/ui.util";

interface Props {
  visible: boolean;
  record?: IChannelMonthlyRevenue | null;
  month?: string;
  onCancel?: () => void;
  onOk?: () => void;
}

interface IForm {
  id?: number;
  channelId?: number;
  taxRate?: number;
  name?: string;
  month?: dayjs.Dayjs;
  amount?: number;
  isInvoiced?: boolean;
  isPaid?: boolean;
  invoiceDate?: string;
  remark?: string;
}

export default function ChannelRevenueModal(props: Props) {
  const [form] = Form.useForm<IForm>();

  const amount = Form.useWatch("amount", form);

  const _handler = {
    onCancel: () => {
      props.onCancel?.();
    },
    onOk: async () => {
      const value: IForm = form.getFieldsValue(true);
      delete value.name;
      const tempValue: Partial<IChannelRevenue> = {
        id: value.id,
        channelId: value.channelId,
        month: +dayjs(value.month).format("YYYYMM"),
        year: +dayjs(value.month).format("YYYY"),
        amount: amountToFen(value.amount || 0),
        isInvoiced: value.isInvoiced,
        isPaid: value.isPaid,
        invoiceDate: value.invoiceDate,
        remark: value.remark,
      };
      if (props.record?.revenues[props.month || ""]?.id) {
        await apiModifyChannelRevenue(
          props.record?.revenues[props.month || ""]?.id,
          tempValue,
        );
      } else {
        await apiAddChannelRevenue(tempValue);
      }
      props.onOk?.();
    },
  };

  useEffect(() => {
    if (!props.visible) {
      return;
    }
    form.setFieldsValue({
      id: props.record?.revenues[props.month || ""]?.id,
      channelId: props.record?.id,
      name: props.record?.name,
      taxRate: props.record?.taxRate,
      month: dayjs(props.month),
      amount: amountToYuan(
        props.record?.revenues[props.month || ""]?.amount || 0,
      ),
      isInvoiced: props.record?.revenues[props.month || ""]?.isInvoiced,
      isPaid: props.record?.revenues[props.month || ""]?.isPaid,
      remark: props.record?.revenues[props.month || ""]?.remark,
    });
  }, [props.record, props.visible, form, props.month]);

  return (
    <Modal
      title={props.record ? "编辑收益记录" : "新增收益记录"}
      open={props.visible}
      maskClosable={false}
      onCancel={_handler.onCancel}
      onOk={_handler.onOk}
      width={800}
    >
      <Form form={form} className="rp-[.ant-form-item]:!mb-0">
        <Title title="渠道基本信息" />
        <div className="my-2 grid grid-cols-2 gap-4 rounded p-4">
          <Form.Item label="渠道名称" name="name">
            <Input disabled />
          </Form.Item>
          <Form.Item label="税点" name="taxRate">
            <Input disabled />
          </Form.Item>
        </div>
        <Title title="收益信息" />
        <div className="my-2 grid grid-cols-3 gap-4 rounded p-4">
          <Form.Item label="月份" name="month" required>
            <DatePicker.MonthPicker className="!w-full" disabled />
          </Form.Item>
          <Form.Item label="收益（元）" name="amount" required>
            <InputNumber precision={2} className="!w-full" />
          </Form.Item>
          <Form.Item>
            <div className="flex !w-full gap-2">
              <div className="flex flex-1 items-center gap-1">
                <span className="text-gray-400">扣税:</span>
                <span className="font-bold text-[#7f8c8d]">
                  {amountToYuan(
                    calculateTaxAmount(
                      amountToFen(amount || 0),
                      props.record?.taxRate || 0,
                    ),
                  )}
                </span>
              </div>
              <div className="flex flex-1 items-center gap-1">
                <span className="text-gray-400">税后:</span>
                <span className="font-bold text-[#2ecc71]">
                  {NP.minus(
                    amount || 0,
                    amountToYuan(
                      calculateTaxAmount(
                        amountToFen(amount || 0),
                        props.record?.taxRate || 0,
                      ),
                    ),
                  )}
                </span>
              </div>
            </div>
          </Form.Item>
        </div>
        <Title title="其他" />
        <div className="my-2 flex flex-col gap-2 rounded p-4">
          <Form.Item label="开票" name="isInvoiced" valuePropName="checked">
            <Checkbox>是否已开票</Checkbox>
          </Form.Item>
          <Form.Item label="打款" name="isPaid" valuePropName="checked">
            <Checkbox>是否已打款</Checkbox>
          </Form.Item>
          <Form.Item label="备注" name="remark">
            <Input.TextArea />
          </Form.Item>
        </div>
      </Form>
    </Modal>
  );
}
